package com.hcjy.controller;

import com.hcjy.common.RegexPatterns;
import com.hcjy.common.exception.UserNotExistException;
import com.hcjy.entity.dto.param.LoginParam;
import com.hcjy.entity.resp.R;
import com.hcjy.service.AuthService;
import com.hcjy.util.SmsUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * @author Guqier
 * @version 1.0
 * @date 2025/6/6 18:55
 */
@RestController
@RequestMapping("/auth")
@RequiredArgsConstructor
public class AuthController {

    private final AuthService authService;

    private final SmsUtils smsUtils;

    /**
     * 用户登录
     * @param loginParam 登录参数
     * @return 登录响应
     */
    @PostMapping("/login")
    public R login(@RequestBody @Validated LoginParam loginParam) {
        try {
            return R.success(authService.login(loginParam.getPhone(), loginParam.getPassword()));
        } catch (UserNotExistException e) {
            return R.fail(R.Archetype.USER_NOT_EXIST);
        }
    }

    /**
     * 用户登出
     * @return 登出响应
     */
    @PostMapping("/logout")
    public R logout() {
        authService.logout();
        return R.success();
    }

    /**
     * 验证手机号
     * @param loginParam 登录参数（包含phone字段）
     * @return 验证响应
     */
    @PostMapping("/sendPhoneVerifyCode")
    public R sendPhoneVerifyCode(@RequestBody LoginParam loginParam) {
        String phone = loginParam.getPhone();
        if (phone == null || phone.isEmpty() || (!phone.matches(RegexPatterns.PHONE_REGEX) && !phone.matches(RegexPatterns.PHONE_REGEX_CN))) {
            return R.fail(R.Archetype.INVALID_PHONE);
        }
        String codeId = smsUtils.sendSmsCode(phone);
        return R.success().of("codeId", codeId);
    }

    /**
     * 验证验证码
     * @param loginParam 登录参数（包含phone、code和codeId字段）
     * @return 验证响应
     */
    @PostMapping("/verifyPhoneCode")
    public R verifyPhoneCode(@RequestBody LoginParam loginParam) {
        if(loginParam.getCode() == null || loginParam.getPhone() == null || loginParam.getCodeId() == null) {
            return R.fail(R.Archetype.PARAM_IS_BLANK);
        }
        return smsUtils.verifyCode(loginParam.getCode(), loginParam.getPhone(), loginParam.getCodeId()) ? R.success() : R.fail(R.Archetype.ERROR_AUTH_CODE);
    }
}
